package com.lc.cehui.app;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.bar.TitleBar;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.lc.cehui.R;
import com.lc.cehui.action.TitleBarAction;
import com.lc.cehui.action.ToastAction;
import com.lc.cehui.base.BaseActivity;
import com.lc.cehui.base.BaseDialog;
import com.lc.cehui.http.model.HttpData;
import com.lc.cehui.http.response.BaseBean;
import com.lc.cehui.ui.activity.ImageBrowseActivity;
import com.lc.cehui.ui.activity.release.CorporateNewsActivity;
import com.lc.cehui.ui.activity.release.TrainingInformationActivity;
import com.lc.cehui.ui.adapter.ImageNineAdapter;
import com.lc.cehui.util.eventbus.Event;
import com.lc.cehui.util.eventbus.EventBusUtils;
import com.lc.cehui.widget.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yalantis.ucrop.view.OverlayView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2018/10/18
 *    desc   : 业务 Activity 基类
 */
public abstract class AppActivity extends BaseActivity
        implements ToastAction, TitleBarAction, OnHttpListener<Object> {

    /** 标题栏对象 */
    private TitleBar mTitleBar;
    /** 状态栏沉浸 */
    private ImmersionBar mImmersionBar;

    /** 加载对话框 */
    private BaseDialog mDialog;
    /** 对话框数量 */
    private int mDialogTotal;

    /**
     * 当前加载对话框是否在显示中
     */
    public boolean isShowDialog() {
        return mDialog != null && mDialog.isShowing();
    }

    /**
     * 显示加载对话框
     */
//    public void showDialog() {
//        mDialogTotal++;
//        postDelayed(() -> {
//            if (mDialogTotal <= 0 || isFinishing() || isDestroyed()) {
//                return;
//            }
//
//            if (mDialog == null) {
//                mDialog = new WaitDialog.Builder(this)
//                        .setCancelable(false)
//                        .create();
//            }
//            if (!mDialog.isShowing()) {
//                mDialog.show();
//            }
//        }, 300);
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isRegisterEventBus() && !EventBus.getDefault().isRegistered(this)) {
            EventBusUtils.register(this);
        }
    }
    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(Event event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(Event event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(Event event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(Event event) {

    }
    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        if (mDialogTotal > 0) {
            mDialogTotal--;
        }

        if (mDialogTotal == 0 && mDialog != null && mDialog.isShowing() && !isFinishing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void initLayout() {
        super.initLayout();

        if (getTitleBar() != null) {
            getTitleBar().setOnTitleBarListener(this);
        }

        // 初始化沉浸式状态栏
        if (isStatusBarEnabled()) {
            getStatusBarConfig().init();

            // 设置标题栏沉浸
            if (getTitleBar() != null) {
                ImmersionBar.setTitleBar(this, getTitleBar());
            }
        }
    }

    /**
     * 是否使用沉浸式状态栏
     */
    protected boolean isStatusBarEnabled() {
        return true;
    }

    /**
     * 状态栏字体深色模式
     */
    public boolean isStatusBarDarkFont() {
        return true;
    }

    /**
     * 获取状态栏沉浸的配置对象
     */
    @NonNull
    public ImmersionBar getStatusBarConfig() {
        if (mImmersionBar == null) {
            mImmersionBar = createStatusBarConfig();
        }
        return mImmersionBar;
    }

    /**
     * 初始化沉浸式状态栏
     */
    @NonNull
    protected ImmersionBar createStatusBarConfig() {
        return ImmersionBar.with(this)
                // 默认状态栏字体颜色为黑色
                .statusBarDarkFont(isStatusBarDarkFont())
                // 指定导航栏背景颜色
                .navigationBarColor(android.R.color.white)
                // 状态栏字体和导航栏内容自动变色，必须指定状态栏颜色和导航栏颜色才可以自动变色
                .autoDarkModeEnable(true, 0.2f);
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(@StringRes int id) {
        setTitle(getString(id));
    }

    /**
     * 设置标题栏的标题
     */
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        if (getTitleBar() != null) {
            getTitleBar().setTitle(title);
        }
    }

    @Override
    @Nullable
    public TitleBar getTitleBar() {
        if (mTitleBar == null) {
            mTitleBar = obtainTitleBar(getContentView());
        }
        return mTitleBar;
    }

    @Override
    public void onLeftClick(View view) {
        onBackPressed();
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
//        overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);
    }

    @Override
    public void finish() {
        super.finish();
//        overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);
    }

    /**
     * {@link OnHttpListener}
     */

    @Override
    public void onStart(Call call) {
//        showDialog();
    }

    @Override
    public void onSucceed(Object result) {
        if (result instanceof HttpData) {
            toast(((HttpData<?>) result).getMessage());
        }
        GsonUtils.fromJson(result.toString(),new TypeToken<BaseBean>(){}.getType());

        BaseBean a = JSON.parseObject("",BaseBean.class);
    }

    @Override
    public void onFail(Exception e) {
        toast(e.getMessage());
    }

    @Override
    public void onEnd(Call call) {
        hideDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isRegisterEventBus() && EventBus.getDefault().isRegistered(this)) {
            EventBusUtils.unregister(this);

        }
        if (isShowDialog()) {
            hideDialog();
        }
        mDialog = null;
    }
    private RxPermissions rxPermissions;
    public void setFooterView(RecyclerView view,ImageNineAdapter adapter,int maxChose,int request) {
        rxPermissions = new RxPermissions(AppActivity.this);
        View footer = LayoutInflater.from(this).inflate(R.layout.adapter_image_footer, view, false);
        ImageView add = footer.findViewById(R.id.iv_add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    int size = adapter.getList().size();
                                    if (size >= maxChose) {
                                        ToastUtils.show("最多选择"+maxChose+"张图片");
                                    } else {
                                        showAlbumlot(request,maxChose - size);
                                    }

                                } else {
                                    ToastUtils.show("请求权限失败");
                                }
                            }
                        });
            }
        });
        adapter.setmFooterView(footer);
    }
    public void startImageBrowse(List<Object> list, int position) {
        //图片放大实现缩放效果
        Intent intent = new Intent(this, ImageBrowseActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("list", JSON.toJSONString(list));
        startActivity(intent);
        overridePendingTransition(R.anim.browser_enter_anim, 0);
    }

    public void showAlbum(int request) {
        //参数很多，根据需要添加
        PictureSelector.create(AppActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.SINGLE)
                .isEnableCrop(true)//是否裁剪
                .freeStyleCropEnabled(true)
                .forResult(request);
    }
    public void showAlbumlot(int request,int max) {
        //参数很多，根据需要添加
        PictureSelector.create(AppActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .selectionMode(PictureConfig.MULTIPLE)
                .maxSelectNum(max)
                .isEnableCrop(false)//是否裁剪
                .freeStyleCropEnabled(true)
                .forResult(request);
    }
    /**
     * 显示空布局
     *
     * @param adapter recyclerView的适配器
     */
    public void showEmptyView(BaseQuickAdapter adapter) {
        setAdapterView(adapter, false);
    }

    /**
     * 显示加载中布局
     *
     * @param adapter recyclerView的适配器
     */
    public void showLoadView(BaseQuickAdapter adapter) {
        setAdapterView(adapter, true);
    }
    public View emptyView;
    /**
     * 设置适配器的空布局
     *
     * @param adapter 适配器
     * @param isLoad  是否是加载中
     */
    public void setAdapterView(BaseQuickAdapter adapter, boolean isLoad) {
        //声明全局变量View emptyView;
        if (emptyView == null) {
            emptyView = getLayoutInflater().inflate(R.layout.view_empty, null);
        }
        ViewGroup parentView = (ViewGroup) emptyView.getParent();
        if (isLoad) {
            emptyView.findViewById(R.id.imageView_img).setVisibility(View.GONE);
            emptyView.findViewById(R.id.progressBar_loading).setVisibility(View.VISIBLE);
        } else {
            emptyView.findViewById(R.id.imageView_img).setVisibility(View.VISIBLE);
            emptyView.findViewById(R.id.progressBar_loading).setVisibility(View.GONE);
        }
        //数据得清空才会显示空布局
        adapter.getData().clear();
        if (emptyView.getParent() != null) {
            parentView.removeView(emptyView);
        }
        adapter.setEmptyView(emptyView);
        adapter.notifyDataSetChanged();
    }

    public boolean callBackCode(BaseBean bean) {
        boolean is = false;
        int code = bean.getCode();
        String msg = bean.getMsg();
        if (code == 200) {
            //请求成功
            is = true;
        } else {
            is = false;
            toast(msg);
        }
        return is;
    }
}